package com.zx.onlineeducation.common.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 *
 * @author 郑雪
 * @since 2022-01-08
 */
public class ExceptionUtil {

    /**
     * 获取异常信息
     *
     * @return java.lang.String
     * @param exception 异常对象
     * @author 郑雪
     * @since 2022-01-08
     */
    public static String getMessage(Exception exception) {
        StringWriter stringWriter = null;
        PrintWriter printWriter = null;
        try {
            stringWriter = new StringWriter();
            printWriter = new PrintWriter(stringWriter);
            // 将出错的栈信息输出到printWriter中
            exception.printStackTrace(printWriter);
            printWriter.flush();
            stringWriter.flush();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
            if (stringWriter != null) {
                try {
                    stringWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return stringWriter.toString();
        }
    }
}
